<template>
    <view class="page-container" :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
      <tn-nav-bar fixed backgroundColor="tn-main-gradient-orangeyellow">
        宝宝资料
        <template slot="right">
          <view class="tn-flex tn-flex-row-center tn-margin-right">
            <tn-button :plain="true" shape="round" class="tn-border tn-border-white tn-color-white"
              @click="saveData" :loading="isLoading">保存</tn-button>
          </view>
        </template>
      </tn-nav-bar>
  
      <view class="content-container">
        <!-- 宝宝姓名 -->
        <view class="input-item">
          <text class="label">宝宝姓名:</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              type="text" 
              v-model="name" 
              placeholder="请输入宝宝姓名"
              style="caret-color: #333;" 
              :focus="nameFocus"
              @focus="onFocus('name')"
              @blur="onBlur('name')"
            />
          </view>
          <text v-if="nameError" class="error">{{ nameError }}</text>
        </view>
  
        <!-- 宝宝性别 -->
        <view class="input-item">
          <text class="label">性别:</text>
          <view class="input-wrapper">
            <view class="gender-selector">
              <view 
                class="gender-option" 
                :class="{ active: sex == 0 }"
                @click="sex = '0'"
              >
                男宝
              </view>
              <view 
                class="gender-option" 
                :class="{ active: sex == 1 }" 
                @click="sex = '1'"
              >
                女宝
              </view>
            </view>
          </view>
        </view>
  
        <!-- 宝宝生日 -->
        <view class="input-item">
          <text class="label">生日:</text>
          <view class="input-wrapper">
            <view class="picker-wrapper" @click="showDatePicker = true">
              <text class="picker-text">{{ birthday || '请选择宝宝生日' }}</text>
              <text class="tn-icon-right"></text>
            </view>

            <tn-picker 
                    v-model="showDatePicker" 
                    mode="time"
                    :defaultTime="birthday"
                    :params="{
                        year: {
                            value: currentYear,
                            start: 2020,
                            end: currentYear
                        },
                        month: {
                            value: currentMonth
                        },
                        day: {
                            value: currentDay
                        },
                        hour: {
                            value: currentHour
                        },
                        minute: {
                            value: currentMinute
                        }
                    }"
                    @confirm="onTimeConfirm" 
                    @cancel="onTimeCancel">
                </tn-picker>
          </view>
          <text v-if="birthdayError" class="error">{{ birthdayError }}</text>
        </view>
      </view>
  
      <view v-if="errorMessage" class="error-message">{{ errorMessage }}</view>
    </view>
  </template>
  
  <script>
  import { mapState, mapActions } from 'vuex';
  import { userSet } from '@/api/user';
  
  export default {
    data() {
      const now = new Date();
      return {
        id: 0,
        name: '',
        sex: 0,
        birthday: '',
        nameError: '',
        birthdayError: '',
        errorMessage: '',
        isLoading: false,
        showDatePicker: false,
        nameFocus: false,
        currentYear: now.getFullYear(),
        currentMonth: now.getMonth() + 1,
        currentDay: now.getDate(),
        currentHour: now.getHours(),
        currentMinute: now.getMinutes(),
        
      };
    },
    computed: {
      ...mapState(['userInfo']),
    },
    onLoad() {
        this.id = this.userInfo.id
        this.name = this.userInfo.name
        this.sex = this.userInfo.sex
        this.birthday = this.userInfo.birthday 
    },
    methods: {
      ...mapActions(['getUserInfo']),
      onTimeConfirm(e) {
            this.birthday = `${e.year}-${String(e.month).padStart(2, '0')}-${String(e.day).padStart(2, '0')} ${String(e.hour).padStart(2, '0')}:${String(e.minute).padStart(2, '0')}`;
            this.showDatePicker = false;
        },
        onTimeCancel() {
            this.showDatePicker = false;
        },
      onFocus(field) {
        this[`${field}Focus`] = true;
      },
      onBlur(field) {
        this[`${field}Focus`] = false;
      },
      async saveData() {
        this.clearErrors();
        if (!this.validateInputs()) return;
  
        this.isLoading = true;
        try {
          const response = await userSet({
            name: this.name,
            sex: this.sex,
            birthday: this.birthday
          });

          if (response) {
            uni.removeStorageSync('USER_INFO');
            this.getUserInfo()
            uni.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          }
        } catch (error) {
          console.error('Error saving child profile:', error);
          this.errorMessage = '保存失败，请重试';
        } finally {
          this.isLoading = false;
        }
      },
      validateInputs() {
        let isValid = true;
        if (!this.name) {
          this.nameError = '请输入宝宝姓名';
          isValid = false;
        }
        if (!this.birthday) {
          this.birthdayError = '请选择宝宝生日';
          isValid = false;
        }
        return isValid;
      },
      clearErrors() {
        this.nameError = '';
        this.birthdayError = '';
        this.errorMessage = '';
      }
    }
  };
  </script>
  
  <style scoped>
  .content-container {
    margin: 20px 26px 0px 26px;
  }
  
  .input-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;
    padding-bottom: 10px;
  }
  
  .label {
    font-weight: bold; 
    margin-right: 10px;
    margin-top: 5px;
    font-size: 16px;
    color: #333;
    width: 80px;
    text-align: left;
  }
  
  .input-wrapper {
    display: flex;
    flex: 1;
    align-items: center;
  }
  
  .input {
    background-color: #F4F4F4;
    height: 40px;
    flex: 1;
    box-sizing: border-box;
    border-radius: 4px;
    font-size: 16px;
  }
  
  .error {
    color: red;
    font-size: 13px;
    margin-top: 5px;
    margin-left: 80px;
  }
  
  .error-message {
    color: red;
    font-size: 14px;
    margin-top: 10px;
    text-align: center;
  }
  
  .picker-wrapper {
    background-color: #F4F4F4;
    padding: 20px 12px;
    flex: 1;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .picker-text {
    font-size: 16px;
    color: #333;
  }
  
  .picker-wrapper .tn-icon-right {
    color: #999;
    font-size: 14px;
    margin-left: 10px;
  }
  
  .gender-selector {
    display: flex;
    width: 100%;
    background-color: #f5f5f5;
    border-radius: 8px;
    padding: 4px;
  }
  
  .gender-option {
    flex: 1;
    text-align: center;
    padding: 8px 0;
    border-radius: 6px;
    font-size: 14px;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
  }
  
  .gender-option.active {
    background-color: #fff;
    color: #ffa500;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    font-weight: 500;
  }
  
  .gender-option:not(.active):hover {
    background-color: rgba(255, 255, 255, 0.5);
  }
  </style>